package com.fkcai.hansoul.common.exception;

import com.fkcai.hansoul.common.util.Result;
import com.fkcai.hansoul.common.util.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.openai.api.common.OpenAiApiClientErrorException;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 * <p>
 *     捕获业务异常，返回错误信息, Controller 层抛出的异常，会进入此方法
 * </p>
 */
@Slf4j
@RestControllerAdvice
public class HandlerGlobalException {
	/**
	 * 业务异常处理
	 * @param e 业务异常
	 * @return 错误信息
	 */
	@ExceptionHandler(ComFoundException.class)
	public Result<Void> handleBusinessException(ComFoundException e) {
		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		
		log.warn("业务异常: {}", e.getMessage());
		return Result.fail(e.getResultCode());
	}
	
	
	/**
	 * 系统异常处理
	 * @param e 系统异常
	 * @return 错误信息
	 */
	@ExceptionHandler(SystemConfigException.class)
	public Result<Void> handleException(SystemConfigException e) {
		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		
		log.error("系统异常: {}", e.getMessage());
		return Result.fail(ResultCode.SYSTEM_ERROR, e.getMessage());
	}
	
	/**
	 * OpenAI API 客户端异常处理
	 * @param e OpenAI API 客户端异常
	 * @return 错误信息
	 */
	@ExceptionHandler(OpenAiApiClientErrorException.class)
	public Result<Void> handleOpenAiException(OpenAiApiClientErrorException e) {
		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		
		log.error("OpenAI API 调用异常: {}", e.getMessage());
		return Result.fail(e.getMessage());
	}
	
	
}
